package com.gkzf.ai.module.crm.util.assembly;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gkzf.ai.module.crm.controller.admin.creditReport.vo.creditreportdetails.CreditReportDetailsSaveReqVO;
import com.gkzf.ai.module.crm.dal.dataobject.creditReport.CreditReportLoanDetailsDO;
import lombok.extern.slf4j.Slf4j;

import java.math.BigDecimal;
import java.util.*;

import static com.gkzf.ai.module.crm.util.AnalysisJsonObjectUtils.*;
import static com.gkzf.ai.module.crm.util.AnalysisJsonObjectUtils.accumulate;

@Slf4j
public class LoanAccountDetails {

    private static final String  OUTSTANDING_LOAN_ACCOUNT_DETAILS = "未结清账户明细列表";

    private static final String  LENDING_INSTITUTION = "贷款机构";

    private static final String  BUSINESS_TYPES = "业务种类";

    public static final String GUARANTY_STYLE = "担保方式";

    public static final String THE_FIVE_CLASS_CLASSIFICATION = "五级分类";

    public static final String LOAN_AMOUNT = "借款金额";

    public static final String MONTHLY_REPAYMENT = "本月应还款";

    public static final String BALANCE = "余额";

    public static final String ACCOUNT_STATUS = "账户状态";

    public static final String FIELD_BALANCE = "balance";

    /**
     *  未结清贷款账户明细
     * @param param 参数Map
     * @param creditReportDetailsSaveReqVO 对象
     * @return
     */
    public void getLoanAccountDetails(Map<String, Object> param, CreditReportDetailsSaveReqVO creditReportDetailsSaveReqVO) {
        List<CreditReportLoanDetailsDO> creditReportLoanOverdueDOList = new ArrayList<>();
        Object loanAccountList = param.get(OUTSTANDING_LOAN_ACCOUNT_DETAILS);
        if (loanAccountList instanceof JSONArray loanAccount) {
            for (Object loanAccountObj : loanAccount) {
                CreditReportLoanDetailsDO creditReportLoanOverdueDO = new CreditReportLoanDetailsDO();
                JSONObject overdueDetailsMap = (JSONObject) loanAccountObj;
                creditReportLoanOverdueDO.setLendingInstitutionName(AssembleUtils.getStringValue(overdueDetailsMap, LENDING_INSTITUTION));
                creditReportLoanOverdueDO.setBusinessTypes(AssembleUtils.getStringValue(overdueDetailsMap, BUSINESS_TYPES));
                creditReportLoanOverdueDO.setGuaranteeMethod(AssembleUtils.getStringValue(overdueDetailsMap, GUARANTY_STYLE));
                creditReportLoanOverdueDO.setFiveLevel(AssembleUtils.getStringValue(overdueDetailsMap, THE_FIVE_CLASS_CLASSIFICATION));
                creditReportLoanOverdueDO.setLoanAmount(AssembleUtils.getStringValue(overdueDetailsMap, LOAN_AMOUNT));
                creditReportLoanOverdueDO.setBalance(AssembleUtils.getStringValue(overdueDetailsMap, BALANCE));
                creditReportLoanOverdueDO.setAccountStatus(AssembleUtils.getStringValue(overdueDetailsMap, ACCOUNT_STATUS));
                creditReportLoanOverdueDO.setMonthlyRepayment(AssembleUtils.getStringValue(overdueDetailsMap, MONTHLY_REPAYMENT));
                creditReportLoanOverdueDOList.add(creditReportLoanOverdueDO);
            }
            creditReportDetailsSaveReqVO.setLoanOverdueDetailsList(creditReportLoanOverdueDOList);
        }

//        getBasicInfoDebt(creditReportLoanOverdueDOList,creditReportDetailsSaveReqVO);
    }

    /**
     * 获取负债概要
     */
    public void getBasicInfoDebt(List<CreditReportLoanDetailsDO> creditReportLoanOverdueDOList,CreditReportDetailsSaveReqVO detailsDO) {
        Map<String,Integer> mechanismNumberMap = new LinkedHashMap<>();
        creditReportLoanOverdueDOList.forEach(creditReportLoanOverdueDO -> {
            // 业务种类
            String business = creditReportLoanOverdueDO.getBusinessTypes();
            // 获取担保方式
            String styleGuaranty =creditReportLoanOverdueDO.getGuaranteeMethod();
            // 账户名称
            String governingBody = creditReportLoanOverdueDO.getLendingInstitutionName();

            Map<String,Object> parenMap = JSON.parseObject(JSON.toJSONString(creditReportLoanOverdueDO), Map.class);

            /*
                取值：信贷交易信息明细-账户，账户状态为非“未结清”，业务种类：个人住房贷款、个人商用房贷款（包括商住两用房），账户数：所有账户数相➕；总余额：所有余额相
             */
            if ((business.contains(PERSONAL_HOUSING_LOAN) || business.contains(PERSONAL_COMMERCIAL_PROPERTY_LOAN))) {
                // 住房按揭
                accumulate(detailsDO, null, parenMap,
                        Integer::parseInt, CreditReportDetailsSaveReqVO::setHousingMortgageAccount,
                        CreditReportDetailsSaveReqVO::getHousingMortgageAccount, 1);
                accumulate(detailsDO, FIELD_BALANCE, parenMap,
                        BigDecimal::new, CreditReportDetailsSaveReqVO::setHousingMortgageMoney,
                        CreditReportDetailsSaveReqVO::getHousingMortgageMoney, null);
            }
            /*
            取值：信贷交易信息明细-账户，账户状态为 “未结清”，业务种类：个人汽车消费贷款，账户数：所有账户数相➕；总余额：所有余额相
             */
            else if (Objects.equals(business, PERSONAL_AUTO_LOAN)) {
                // 车辆按揭
                accumulate(detailsDO, null, parenMap,
                        Integer::parseInt, CreditReportDetailsSaveReqVO::setVehicleAccount,
                        CreditReportDetailsSaveReqVO::getVehicleAccount, 1);
                accumulate(detailsDO, FIELD_BALANCE, parenMap,
                        BigDecimal::new, CreditReportDetailsSaveReqVO::setVehicleMoney,
                        CreditReportDetailsSaveReqVO::getVehicleMoney, null);
            }
            /*
            取值：信贷交易信息明细-（非循环贷账户、循环贷账户一、循环贷账户二）所有管理机构：账户状态为为 “未结清”，名称判断有【银行】汉字，机构数：所有机构数相➕；总余额：所有余额相➕
             */
                // 贷款的管理不机构不为空并且存在银行字符  则为银行按揭 否则为非银行按揭
                if (Objects.nonNull(governingBody) && governingBody.contains(BANK)) {
                    // 银行按揭
                    accumulate(detailsDO, null, parenMap,
                            Integer::parseInt, CreditReportDetailsSaveReqVO::setBankingOrganizationAccount,
                            CreditReportDetailsSaveReqVO::getBankingOrganizationAccount, 1);
                    accumulate(detailsDO, FIELD_BALANCE, parenMap,
                            BigDecimal::new, CreditReportDetailsSaveReqVO::setBankingOrganizationMoney,
                            CreditReportDetailsSaveReqVO::getBankingOrganizationMoney, null);
                }
                /*
                取值：信贷交易信息明细-（非循环贷账户、循环贷账户一、循环贷账户二）所有管理机构：账户状态为为 “未结清”，名称判断无【银行】汉字，机构数：所有机构数相➕；总余额：所有余额相
                 */
                else {
                    // 非银行按揭
                    accumulate(detailsDO, null, parenMap,
                            Integer::parseInt, CreditReportDetailsSaveReqVO::setNonBankingOrganizationAccount,
                            CreditReportDetailsSaveReqVO::getNonBankingOrganizationAccount, 1);
                    accumulate(detailsDO, FIELD_BALANCE, parenMap,
                            BigDecimal::new, CreditReportDetailsSaveReqVO::setNonBankingOrganizationMoney,
                            CreditReportDetailsSaveReqVO::getNonBankingOrganizationMoney, null);
                }

            /*
            取值：信贷交易信息明细-（非循环贷账户、循环贷账户一、循环贷账户二）所有管理机构：账户状态：未结清 担保方式为：信用/无担保、保证，的所有机构数，机构数需要去重
            取值：信贷交易信息明细-（非循环贷账户、循环贷账户一、循环贷账户二）所有管理机构：账户状态：未结清 担保方式为：信用/无担保、保证，的所有机构数，机构数下的所有余额总和
              信用贷款 信息
              1.    计算 信用贷款 账户状态未结清 && 非信用卡 && 担保方式为 信用/无担保
              2.    计算五级分类 账户状态未结清 && 非信用卡
             */
            //账户状态未结清 && 非信用卡
                // 计算 信用贷款  担保方式为 信用/无担保
                if (Objects.equals(styleGuaranty, CREDIT_NO_GUARANTEE)) {
                    // 信用贷款机构不重复
                    if (!mechanismNumberMap.containsKey("details" + governingBody)) {
                        mechanismNumberMap.put("details" + governingBody, 1);
                        // 信用贷款
                        accumulate(detailsDO, null, parenMap,
                                Integer::parseInt, CreditReportDetailsSaveReqVO::setCreditLoanOrgCount,
                                CreditReportDetailsSaveReqVO::getCreditLoanOrgCount, 1);
                    }
                    // 余额计算重复的机构余额
                    accumulate(detailsDO, FIELD_BALANCE, parenMap,
                            BigDecimal::new, CreditReportDetailsSaveReqVO::setCreditLoanMoneyCount,
                            CreditReportDetailsSaveReqVO::getCreditLoanMoneyCount, null);
                }
        });

    }
}
